﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.GridPerson;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MD5Hash;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.GridPerson
{
    /// <summary>
    /// 创建网格人员的中介者处理类
    /// </summary>
    public class CreateGridPersonHandler : IRequestHandler<CreateGridPersonCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreateGridPersonHandler> logger;
        /// <summary>
        /// 通过构造函数注入中介者所需的资源
        /// </summary>
        /// <param name="accRepo">账号仓储</param>
        /// <param name="mapper">AutoMapper 组件</param>
        /// <param name="logger">Nlog日志组件</param>
        public CreateGridPersonHandler(IBaseRepository<AccountModel> accRepo,IMapper mapper,ILogger<CreateGridPersonHandler> logger)
        {
            this.accRepo = accRepo;
            this.mapper = mapper;
            this.logger = logger;
        }


        /// <summary>
        /// 创建网格人员的中介者处理方法
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>响应包装类</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateGridPersonCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            logger.LogInformation("正在添加新的网格人员:"+request.RealName);

            var accountCount = accRepo.GetAll().Where(x => x.Name == request.Name).Count();
            if (accountCount > 0) {
                result.Code = ApiEnums.Error;
                result.Msg = "用户名已存在,换个用户名";
                result.Data = 0;
                return Task.FromResult(result);
            }

            var model = mapper.Map<AccountModel>(request);   
            model.Id = YitIdHelper.NextId();
            model.Pass = request.Card.Substring(request.Card.Length - 6, 6).GetMD5();//密码是身份证的后六位
            //id?

            //密码?
            var r = accRepo.Create(model);
            if (r > 0)
            {
                result.Code = ApiEnums.Success;
                result.Msg = "添加成功!";
                result.Data = r;
            }
            else {
                result.Code = ApiEnums.Fail;
                result.Msg = "添加失败!";
                result.Data = r;
            }
            return Task.FromResult(result);
                 
        }
    }
}
